package org.trade.coupon.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.trade.common.constant.TradeEnums;
import org.trade.common.protocol.coupon.ChangeCoponStatusReq;
import org.trade.common.protocol.coupon.ChangeCoponStatusRes;
import org.trade.common.protocol.coupon.QueryCouponReq;
import org.trade.common.protocol.coupon.QueryCouponRes;
import org.trade.coupon.service.ICouponService;
import org.trade.entity.TradeCoupon;
import org.trade.mapper.TradeCouponMapper;

@Service
public class CouponServiceImpl implements ICouponService {
	@Autowired
	private TradeCouponMapper tradeCouponMapper;

	public QueryCouponRes queryCoupon(QueryCouponReq queryCouponReq) {
		QueryCouponRes queryCouponRes = new QueryCouponRes();
		queryCouponRes.setRetCode(TradeEnums.RetEnum.SUCCESS.getCode());
		queryCouponRes.setRetInfo(TradeEnums.RetEnum.SUCCESS.getDesc());
		try {
			if (queryCouponReq == null || StringUtils.isBlank(queryCouponReq.getCouponId())) {
				throw new Exception("请求参数不正确,优惠券编号为空");
			}
			TradeCoupon tradeCoupon = this.tradeCouponMapper.selectByPrimaryKey(queryCouponReq.getCouponId());
			if (tradeCoupon != null) {
				BeanUtils.copyProperties(tradeCoupon, queryCouponRes);
			} else {
				throw new Exception("未查询到该优惠券");
			}
		} catch (Exception ex) {
			queryCouponRes.setRetCode(TradeEnums.RetEnum.FAIL.getCode());
			queryCouponRes.setRetInfo(ex.getMessage());
		}
		return queryCouponRes;
	}

	@Transactional
	public ChangeCoponStatusRes changeCoponStatus(ChangeCoponStatusReq changeCoponStatusReq) {
		ChangeCoponStatusRes changeCoponStatusRes = new ChangeCoponStatusRes();
		changeCoponStatusRes.setRetCode(TradeEnums.RetEnum.SUCCESS.getCode());
		changeCoponStatusRes.setRetInfo(TradeEnums.RetEnum.SUCCESS.getDesc());
		try {
			if (changeCoponStatusReq == null || StringUtils.isBlank(changeCoponStatusReq.getCouponId())) {
				throw new Exception("请求参数不正确,优惠券编号为空");
			}
			TradeCoupon tradeCoupon = new TradeCoupon();
			tradeCoupon.setCouponId(changeCoponStatusReq.getCouponId());
			tradeCoupon.setOrderId(changeCoponStatusReq.getOrderId());
			if (changeCoponStatusReq.getIsUsed().equals(TradeEnums.YesNoEnum.YES.getCode())) {
				int reocrd = tradeCouponMapper.useCoupon(tradeCoupon);
				if (reocrd <= 0) {
					throw new Exception("使用优惠券失败");
				}
			} else if (changeCoponStatusReq.getIsUsed().equals(TradeEnums.YesNoEnum.NO.getCode())) {
				tradeCouponMapper.unUseCoupon(tradeCoupon);
			}
		} catch (Exception ex) {
			changeCoponStatusRes.setRetCode(TradeEnums.RetEnum.FAIL.getCode());
			changeCoponStatusRes.setRetInfo(ex.getMessage());
		}
		return changeCoponStatusRes;
	}

}
